/*
 * VentasManagerFrm.java
 *
 * Created on 6 de marzo de 2007, 09:38 AM
 */

package inc.jmc.cyberboard.ui.ventas;

import inc.jmc.cyberboard.common.DefaultLookAndFeel;
import inc.jmc.cyberboard.common.ImageLoader;
import inc.jmc.cyberboard.dao.HistoricoVentasDao;
import inc.jmc.cyberboard.entitybeans.HistoricoVentas;
import inc.jmc.cyberboard.ui.CyberManager;
import inc.jmc.cyberboard.ui.ventas.common.FiltroVentas_VentaAnualPane;
import inc.jmc.cyberboard.ui.ventas.common.FiltroVentas_VentaMensualPane;
import inc.jmc.cyberboard.ui.ventas.common.FiltroVentas_VentasPeriodoPane;
import inc.jmc.cyberboard.ui.ventas.common.FiltroVentas_VentasPorDiaPane;
import java.awt.Insets;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.swing.JFileChooser;

import org.apache.log4j.Logger;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author  Juan Miguel Olguin Salguero
 */
public class VentasManagerFrm extends javax.swing.JInternalFrame {
    
    static Logger logger = Logger.getLogger(VentasManagerFrm.class.getName());
    FiltroVentas_VentaAnualPane anualp=new  FiltroVentas_VentaAnualPane();
    FiltroVentas_VentaMensualPane mensualp=new  FiltroVentas_VentaMensualPane();
    FiltroVentas_VentasPeriodoPane periodop = new  FiltroVentas_VentasPeriodoPane(CyberManager.currentLocale);
    FiltroVentas_VentasPorDiaPane diap=new  FiltroVentas_VentasPorDiaPane(CyberManager.currentLocale);
    HistoricoGridVentas historicoGrid=null;
    DetalleGridVentasSimple historicoGridDetalle = null;
    JPanel[] arryPane = new JPanel[]{diap,periodop,mensualp,anualp};
    
    
    
    public VentasManagerFrm() {
        initComponents();
        applyFilterButton.setMargin(new Insets(0,0,0,0));
        
        logger.info("Estamos creando VentasManagerFrm");
        historicoGrid=new HistoricoGridVentas(this);///cargamos todos los registros del mes por default
        historicoGridDetalle=new DetalleGridVentasSimple();///cargamos todos los registros del mes por default
        historicoGrid.addListSelectionListener(historicoGridDetalle);//al historico le agregamos el listener para que cuando se
                                                                     //haga clic en el registro, se actualice.
        this.getCountTxt().setText(""+historicoGrid.rowCount());
        jSplitPane1.setLeftComponent(historicoGrid);
        jSplitPane1.setRightComponent(historicoGridDetalle);
        
        for(int i=0;i<arryPane.length;i++)
        {
            arryPane[i].setBounds(10, 70, 210, 245);
            jPanel5.add(arryPane[i]);
        }
        
        setVisibleFiltro(-1);//no queremos mostrar ningun tablero de filtros
        iniTextFields();
        
        filtroCmb.setSelectedIndex(0);
        if(historicoGrid.rowCount()>0)
    	{
        	historicoGrid.setSelectionIndex(0);
    	}
        
        settingInternalFrame();
        this.updateUI();
    }
    
    public void setTipoUser(String tipoUser)
    {
    	if(!tipoUser.equalsIgnoreCase("Administrador"))
    		borrarRegistroButton.setEnabled(false);
    }
    /*void initSelection()
    {
    	if(historicoGrid.rowCount()>0)
    	{
    	historicoGrid.setSelectionIndex(0);
    	if(historicoGrid.rowCount()>1)
    		historicoGrid.setSelectionIndex(1);
    	historicoGrid.setSelectionIndex(0);
    	}
    }*/
    
    void setVisibleFiltro(int i)
    {
        arryPane[0].setVisible(false);
        arryPane[1].setVisible(false);
        arryPane[2].setVisible(false);
        arryPane[3].setVisible(false);
        if(i>=0 && i<arryPane.length)
           arryPane[i].setVisible(true);
        anualp.initYearsList();
        this.updateUI();
    }
    void iniTextFields()
    {
    
        this.getCountTxt().setFont(DefaultLookAndFeel.TableFont2);
        this.getCountTxt().setBackground(DefaultLookAndFeel.TableBackground);
        this.getItemsCountTxt().setFont(DefaultLookAndFeel.TableFont2);
        this.getItemsCountTxt().setBackground(DefaultLookAndFeel.TableBackground);
        this.getSubtotalTxt().setFont(DefaultLookAndFeel.TableFont3);
        this.getSubtotalTxt().setBackground(DefaultLookAndFeel.TableBackground);
        this.getIvaTxt().setFont(DefaultLookAndFeel.TableFont3);
        this.getIvaTxt().setBackground(DefaultLookAndFeel.TableBackground);
        this.getTotalTxt().setFont(DefaultLookAndFeel.TableFont3);
        this.getTotalTxt().setBackground(DefaultLookAndFeel.TableBackground);
        
        this.getCountTxt().setEditable(false);
        this.getItemsCountTxt().setEditable(false);
        this.getSubtotalTxt().setEditable(false);
        this.getIvaTxt().setEditable(false);
        this.getTotalTxt().setEditable(false);
        
    
    }
    void settingInternalFrame()
    {
        this.setSize(947,537);
        this.setResizable(true);
        this.setMaximizable(false);
        this.setIconifiable(false);
        this.setClosable(true);
        this.setFrameIcon(ImageLoader.images[ImageLoader.ICON_FRAME_MAIN]);
        this.updateUI();
    }

    public javax.swing.JTextField getCountTxt() {
        return countTxt;
    }

    public javax.swing.JTextField getItemsCountTxt() {
        return itemsCountTxt;
    }

    public javax.swing.JTextField getIvaTxt() {
        return ivaTxt;
    }

    public javax.swing.JTextField getSubtotalTxt() {
        return subtotalTxt;
    }

    public javax.swing.JTextField getTotalTxt() {
        return totalTxt;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        borrarRegistroButton = new javax.swing.JButton();
        exportarButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        filtroCmb = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        applyFilterButton = new javax.swing.JButton();
        recordsLabel = new javax.swing.JLabel();
        countTxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        itemsCountTxt = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        subtotalTxt = new javax.swing.JTextField();
        ivaTxt = new javax.swing.JTextField();
        totalTxt = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel6 = new javax.swing.JPanel();
        jPanel7 = new javax.swing.JPanel();

        setTitle("Consulta de Ventas ");
        setPreferredSize(new java.awt.Dimension(600, 438));
        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(null);

        jPanel2.setMaximumSize(new java.awt.Dimension(100, 100));
        jPanel2.setMinimumSize(new java.awt.Dimension(100, 100));
        jPanel2.setPreferredSize(new java.awt.Dimension(260, 160));
        jPanel4.setLayout(null);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Regsitro"));
        borrarRegistroButton.setText("Borrar");
        borrarRegistroButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                borrarRegistroButtonActionPerformed(evt);
            }
        });

        jPanel4.add(borrarRegistroButton);
        borrarRegistroButton.setBounds(20, 20, 80, 23);

        exportarButton.setText("Exportar");
        exportarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportarButtonActionPerformed(evt);
            }
        });

        jPanel4.add(exportarButton);
        exportarButton.setBounds(110, 20, 110, 23);

        jPanel2.add(jPanel4);
        jPanel4.setBounds(10, 10, 240, 50);

        jPanel5.setLayout(null);

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtro"));
        filtroCmb.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Venta de hoy", "Venta por dia", "Venta por periodo", "Venta mensual", "Venta anual", "Todos los registros" }));
        filtroCmb.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                filtroCmbItemStateChanged(evt);
            }
        });

        jPanel5.add(filtroCmb);
        filtroCmb.setBounds(10, 40, 140, 22);

        jLabel1.setText("Selecciona  filtro");
        jPanel5.add(jLabel1);
        jLabel1.setBounds(10, 20, 120, 14);

        applyFilterButton.setText("Aplicar");
        applyFilterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyFilterButtonActionPerformed(evt);
            }
        });

        jPanel5.add(applyFilterButton);
        applyFilterButton.setBounds(153, 40, 65, 23);

        recordsLabel.setText("Registros:");
        jPanel5.add(recordsLabel);
        recordsLabel.setBounds(10, 330, 70, 14);

        countTxt.setEditable(false);
        countTxt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel5.add(countTxt);
        countTxt.setBounds(90, 330, 130, 19);

        jLabel2.setText("Articulos");
        jPanel5.add(jLabel2);
        jLabel2.setBounds(10, 350, 70, 14);

        itemsCountTxt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel5.add(itemsCountTxt);
        itemsCountTxt.setBounds(90, 349, 130, 20);

        jLabel3.setText("Subtotal");
        jPanel5.add(jLabel3);
        jLabel3.setBounds(10, 370, 70, 14);

        subtotalTxt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel5.add(subtotalTxt);
        subtotalTxt.setBounds(90, 370, 130, 19);

        ivaTxt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel5.add(ivaTxt);
        ivaTxt.setBounds(90, 390, 130, 19);

        totalTxt.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        jPanel5.add(totalTxt);
        totalTxt.setBounds(90, 410, 130, 19);

        jLabel4.setText("Iva");
        jPanel5.add(jLabel4);
        jLabel4.setBounds(10, 390, 70, 14);

        jLabel5.setText("Total");
        jPanel5.add(jLabel5);
        jLabel5.setBounds(10, 410, 70, 14);

        jPanel2.add(jPanel5);
        jPanel5.setBounds(10, 60, 240, 440);

        jPanel1.add(jPanel2, java.awt.BorderLayout.EAST);

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel3.setMaximumSize(new java.awt.Dimension(100, 100));
        jPanel3.setMinimumSize(new java.awt.Dimension(100, 100));
        jSplitPane1.setDividerLocation(400);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setLeftComponent(jPanel6);

        jSplitPane1.setRightComponent(jPanel7);

        jPanel3.add(jSplitPane1, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel3, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    String exportar1Path="";
    private void exportarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarButtonActionPerformed

        JFileChooser jfc=new JFileChooser(exportar1Path);
        
        jfc.setFileFilter(new CSVFileFilter());
        int a=jfc.showSaveDialog(this);
        if(a==JFileChooser.APPROVE_OPTION)
        {
            File file=jfc.getSelectedFile();
            if(file.exists())
            {
            	int opti = JOptionPane.showConfirmDialog(this, "Desea sobreescribir el archivo?", "Archivo existente", JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
            	if(opti==JOptionPane.NO_OPTION)
            		return;
            	
            	
            }
            exportar1Path=file.getPath();
            if(!exportar1Path.toLowerCase().endsWith("csv"))
            {
                exportar1Path=exportar1Path+".csv";
            }
            StringBuffer content1 = this.historicoGrid.exportToCSV_ReporteVentas();
            FileWriter fw; 
            try {
            	
		fw=new FileWriter(exportar1Path);
		fw.write(content1.toString());
		fw.close();
		JOptionPane.showMessageDialog(this,"El archivo se exporto exitosamente","Exportar arcivo",JOptionPane.INFORMATION_MESSAGE);
		} 
            catch (IOException e) {
                JOptionPane.showMessageDialog(this,"Error al exportar archivo:"+e.getMessage(),"Error IO",JOptionPane.ERROR_MESSAGE);
		e.printStackTrace();
	    }
            
            
        }
    }//GEN-LAST:event_exportarButtonActionPerformed

    private void borrarRegistroButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_borrarRegistroButtonActionPerformed

        HistoricoVentas ndx1 = (HistoricoVentas)historicoGrid.getSelectedItem();
        if(ndx1==null)
        {
            JOptionPane.showMessageDialog(this,"No existen registros seleccionados","No hay registros",JOptionPane.ERROR_MESSAGE);
            return;
        }
        //aqui debemos llamar a la accion de borrado en la base de datos
        String[] ops=new String[]{"Si","No"};
    	int a=JOptionPane.showOptionDialog(
                this,
                "Desea borrar este registro?",
                "Borrado de datos",
                JOptionPane.DEFAULT_OPTION,
                JOptionPane.WARNING_MESSAGE,
                null,
                ops,
                ops[0]);
          if(a==JOptionPane.YES_OPTION)
          {
    	
		        try {
					Connection conn= inc.jmc.cyberboard.dao.Dao.getConnection();
					HistoricoVentasDao dao=new HistoricoVentasDao();
					ndx1 = (HistoricoVentas)historicoGrid.getSelectedItem();
					if(ndx1!=null && ndx1.getIdVenta()!=null)
                                            dao.deleteVentaID(conn, ndx1.getIdVenta().intValue());
					conn.close();
					historicoGrid.loadProductsBD();
                    historicoGrid.addListSelectionListener(historicoGridDetalle);
                    if(historicoGrid.dataProductos.size()>0)
                    	historicoGrid.setSelectionIndex(0);
                    JOptionPane.showMessageDialog(this,"Registro eliminado ok", "Eliminacion de registro",JOptionPane.INFORMATION_MESSAGE);
					 
				} 
				catch (SQLException e) {
					logger.info("EXCEPTION EXCEPTION "+e.getMessage());
					e.printStackTrace();
				}
				catch (Exception e) {
						logger.info("EXCEPTION EXCEPTION "+e.getMessage());
						e.printStackTrace();
				}
			}
        
        
        
    }//GEN-LAST:event_borrarRegistroButtonActionPerformed

    private void filtroCmbItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_filtroCmbItemStateChanged

        int ndx = filtroCmb.getSelectedIndex();
        if(ndx ==0 || ndx ==5) //ES LA VENTA DE HOY
        {
            //SOLO SE APLICA EL FILTRO de la venta de hoy
            setVisibleFiltro(-1);
        }
        else
        {
            setVisibleFiltro(ndx-1);
        }
    }//GEN-LAST:event_filtroCmbItemStateChanged

    private void applyFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyFilterButtonActionPerformed

        int i = this.filtroCmb.getSelectedIndex();
        switch (i) {
		case HistoricoVentasDao.QUERY_VENTA_HOY:
			historicoGrid.setQueryType(HistoricoVentasDao.QUERY_VENTA_HOY);
			break;
		case HistoricoVentasDao.QUERY_VENTA_POR_DIA:
			historicoGrid.setQueryType(HistoricoVentasDao.QUERY_VENTA_POR_DIA);
			historicoGrid.setFecha1(this.diap.getInidateTxt().getText());
			break;
		case HistoricoVentasDao.QUERY_VENTA_POR_PERIODO:
			historicoGrid.setQueryType(HistoricoVentasDao.QUERY_VENTA_POR_PERIODO);
			historicoGrid.setFecha1(this.periodop.getInidateTxt().getText());
			historicoGrid.setFecha2(this.periodop.getFindateTxt().getText());
			break;
		case HistoricoVentasDao.QUERY_VENTA_MENSUAL:
			historicoGrid.setQueryType(HistoricoVentasDao.QUERY_VENTA_MENSUAL);
			String fechaaux= "";
			fechaaux ="1/"+(""+(this.mensualp.getMesCmb().getSelectedIndex()+1)) + "/2007";
			historicoGrid.setFecha1(fechaaux);
			break;
		case HistoricoVentasDao.QUERY_VENTA_ANUAL:
			historicoGrid.setQueryType(HistoricoVentasDao.QUERY_VENTA_ANUAL);
			String fechaaux2= "";
			fechaaux2 ="1/01/"+(String)this.anualp.getYearCmb().getSelectedItem();
			historicoGrid.setFecha1(fechaaux2);
			break;
			
		case HistoricoVentasDao.QUERY_ALL_RECORDS:
			historicoGrid.setQueryType(HistoricoVentasDao.QUERY_ALL_RECORDS);
			break;

		default:
			break;
		}
        
        try {
			historicoGrid.loadProductsBD();
            historicoGridDetalle.removeAll();
			historicoGrid.addListSelectionListener(historicoGridDetalle);
			if(historicoGrid.rowCount()>0)
	    	{
	        	historicoGrid.setSelectionIndex(0);
	    	}
		} catch (Exception e) {
			logger.error(""+e.getMessage());
			e.printStackTrace();
		}
        this.getCountTxt().setText(""+historicoGrid.rowCount());
        
        
        

    }//GEN-LAST:event_applyFilterButtonActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyFilterButton;
    private javax.swing.JButton borrarRegistroButton;
    private javax.swing.JTextField countTxt;
    private javax.swing.JButton exportarButton;
    private javax.swing.JComboBox filtroCmb;
    private javax.swing.JTextField itemsCountTxt;
    private javax.swing.JTextField ivaTxt;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel recordsLabel;
    private javax.swing.JTextField subtotalTxt;
    private javax.swing.JTextField totalTxt;
    // End of variables declaration//GEN-END:variables
    
}
